package com.yyge.base

import android.content.ContentValues.TAG
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleObserver

/**
 * 所有Fragment的基类
 */
abstract class BaseFragment:Fragment(), LifecycleObserver {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        init()
        Log.i(TAG, "onCreate: 6666666666666")
    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return initView()
    }

    /**
     * 获取布局View
     */
    abstract fun initView(): View?

    override fun onAttach(context: Context) {
        super.onAttach(context)
        requireActivity().lifecycle.addObserver(LifecycleEventObserver { source, event ->
            if (event.targetState == Lifecycle.State.CREATED) {
                initListener()
                initData()
                requireActivity().lifecycle.removeObserver(this) // 移除观察者
            }
        })
    }

    /**
     * 数据初始化
     */
    protected fun initData(){

    }

    /**
     * adapter 和listener的相关操作
     */
    protected fun initListener(){

    }

    /**
     * Fragment 初始化
     */
    protected fun init() {

    }


     fun print(msg:String){
         this.activity?.runOnUiThread{
             Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
         }
    }
}